package com.steve.xfood.handler;

import com.steve.xfood.VO.ResultVO;
import com.steve.xfood.config.ProjectUrlConfig;
import com.steve.xfood.config.WeChatAccountConfig;
import com.steve.xfood.config.WeChatOpenConfig;
import com.steve.xfood.exception.SellerAuthorizeException;
import com.steve.xfood.exception.XFoodException;
import com.steve.xfood.util.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 * 用户登录全局异常捕获
 * @author steve
 * @date 2020/5/27 14:35
 */
@ControllerAdvice
public class SellerExceptionHandler {
    @Autowired
    private ProjectUrlConfig projectUrlConfig;
    @Autowired
    private WeChatAccountConfig accountConfig;

    private static final String OPENID = "oTgZpwdZi_KC40hZHU-YmlWogkHU";

    /**
     * 拦截登录异常SellerAuthorizeException
     * https://open.weixin.qq.com/connect/qrconnect?appid=wx6ad144e54af67d87&redirect_uri=http://sell.springboot.cn/sell/qr/oTgZpwdZi_KC40hZHU-YmlWogkHU&response_type=code&scope=snsapi_login&state=http://xfood.nat300.top/sell/wechat/qrUserInfo
     */
    @ExceptionHandler(SellerAuthorizeException.class)
    public ModelAndView handlerAuthorizeException() {
        //出现异常则重定向到扫码登录页面
        return new ModelAndView("redirect:"
                .concat("https://open.weixin.qq.com/connect/qrconnect")
                .concat("?appid="+ accountConfig.getOpenAppId() +"&redirect_uri=")
                .concat("http://sell.springboot.cn/sell/qr/"+ OPENID)
                .concat("&response_type=code&scope=snsapi_login&state=")
                .concat(projectUrlConfig.getWechatOpenAuthorize() + "/sell/wechat/qrUserInfo"));
    }

    /**
     * 捕获自定义异常，并返回ResultVO格式
     * @ResponseStatus(HttpStatus.FORBIDDEN) 自定义返回的状态码
     * @param e 自定义异常
     * @return
     */
    @ExceptionHandler(XFoodException.class)
    @ResponseBody
    //@ResponseStatus(HttpStatus.FORBIDDEN)
    public ResultVO handlerXFoodException(XFoodException e) {
        return ResultVOUtil.error(e.getCode(), e.getMessage());
    }
}
